from docutils.parsers import rst
from docutils.parsers.rst.directives import body
from docutils.parsers.rst import directives
from pennypress.apps.ReST import uri_resolver
from django.utils.synch import RWLock
lock = RWLock()

def register_directive(directive_name, directive_class):
    """This docutil's register_directive is not threadsafe, use this one"""
    lock.writer_enters()
    try:
        directives.register_directive(directive_name, directive_class)
    finally:
        lock.writer_leaves()
    
def django_sidebar(name, arguments, options, content, lineno, content_offset,
                   block_text, state, state_machine):
    from pennypress.apps.ReST.markup import markup_parts
    # Get the model's uri
    model_uri = arguments[0]

    # Use the uri resolver to get the object's instance
    obj = uri_resolver.resolve(model_uri)
    
    # Get the template name option or the default from the app_label
    template_name = options.get('template_name', 'sidebars/%s.rst' % \
                                    obj._meta.app_label)

    # Render the django template
    t = loader.get_template(template_name)
    rest_source = t.render(Context({ 'object': obj}))

    # Treat the django template as ReST
    parts = markup_parts(rest_source)

    # If the rendered content has a title, use it for the sidebar title
    if parts.get("title", None):
        options['title'] = parts['title']

    # If the rendered content has a subtitle, use it for the sidebar subtitle
    if parts.get("subtitle", None):
        options['subtitle'] = parts['subtitle']
        
    # Set the sidebar content as the fragment of the template
    options['content'] = parts['fragment']

    return body.sidebar(name, arguments, options, content, lineno, 
                        content_offset, block_text, state, state_machine)
